<template>
  <div id="app">
    <div>
      <span>姓名:</span>
      <input type="text" v-model.trim="name"/>
    </div>
    <div>
      <span>年龄:</span>
      <input type="number" v-model.number.trim="age"/>
    </div>
    <div>
      <span>性别:</span>
      <select v-model="sex">
        <option value="男">男</option>
        <option value="女">女</option>
      </select>
    </div>
    <div>
      <button @click="add">添加/修改</button>
    </div>
    <div>
      <table
          border="1"
          cellPadding="10"
          cellSpacing="0"
      >
        <tr>
          <th>序号</th>
          <th>姓名</th>
          <th>年龄</th>
          <th>性别</th>
          <th>操作</th>
        </tr>
        <tr v-for="obj in list" :key="obj.id">
          <td>{{ obj.id }}</td>
          <td>{{ obj.name }}</td>
          <td>{{ obj.age }}</td>
          <td>{{ obj.sex }}</td>
          <td>
            <button @click="del(index)">删除</button>
            <button @click="edit(index)">编辑</button>
          </td>
        </tr>
      </table>
    </div>
    <div>总共岁数：{{ageSum}}</div>
  </div>
</template>
<script>
export default {
  data() {
    return {
      list: [
        {
          id: 1,
          name: '小明',
          age: 14,
          sex: '男'
        }
      ]
    }
  },
  methods: {
    add() {
      const lastId = this.list.length ? this.list[this.list.length - 1].id : 1
      this.list.push({
        id: lastId+1,
        name: this.name,
        age: this.age,
        sex: this.sex
      })
    },
    del(index) {
      this.list.splice(index,1)
    }
  },
  computed:{
    ageSum(){
      return this.list.reduce((sum,obj)=>{
        return sum += obj.age
      },0)
    }
  }
}
</script>
